package com.huanbao.uav.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@Component
@WebFilter(urlPatterns = "/**", filterName = "indexFilter")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@Slf4j
public class CORSFilter implements Filter
{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 设置SessionId

        String requestId = null;
        if(request instanceof HttpServletRequest) {
            HttpServletRequest req=(HttpServletRequest) request;

            final String dheader=req.getHeader("x-req-id");
            if(StringUtils.isNotBlank(dheader)) {
                log.debug("over set request id. new:"+dheader);
                requestId=dheader;
            }
        }
        if(StringUtils.isBlank(requestId)) {
            requestId=UUID.randomUUID().toString().replace("-", "");
        }

        MDC.put("x-req-id", requestId);

        log.debug("curren run request x-req-id: "+requestId +" ,url: "+request.getRequestURL().toString()+"?"+StringUtils.trimToEmpty(request.getQueryString()));

        String method = request.getMethod();

        try {
            if (method.equalsIgnoreCase("OPTIONS"))
            {
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(HttpStatus.OK.value());
            }
            else
            {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }finally {
            MDC.remove("x-req-id");
        }

    }

    @Override
    public void destroy()
    {

    }

}